from rest_framework.viewsets import GenericViewSet

from api.extension.mixins import DigListModelMixin, DigCreateModelMixin
from api.extension.filter import SelfFilterBackend
from django_filters.rest_framework import DjangoFilterBackend
from django_filters import FilterSet, filters
from api import models
from api.serializers.news import NewsSerializer, IndexModelSerializer
from api.extension.throttle import NewsCreateRateThrottle
from api.extension.auth import UserAnonTokenAuthentication


class NewsFilterSet(FilterSet):
    latest_id = filters.NumberFilter(field_name='id', lookup_expr='lt')

    class Meta:
        model = models.News
        fields = ["latest_id", ]


class NewsView(GenericViewSet, DigListModelMixin, DigCreateModelMixin):
    filter_backends = [SelfFilterBackend, DjangoFilterBackend]
    filterset_class = NewsFilterSet

    # 未删除 & 属于当前用户创建的新闻资讯
    queryset = models.News.objects.filter(deleted=False).order_by('-id')
    serializer_class = NewsSerializer

    throttle_objects = [NewsCreateRateThrottle(), ]

    def perform_create(self, serializer):
        # 1.创建新闻资讯
        # 2.自己对自己的内容做推荐
        #       - 推荐数量+1
        #       - 推荐记录  用户&资讯
        serializer.save(user=self.request.user)

        # 当创建成功 在调用限流
        for throttle in self.get_throttles():
            throttle.done()

    # 访问创建页面的时候调用限流类
    def get_throttles(self):
        if self.request.method == "POST":
            return self.throttle_objects
        return []


class IndexFilterSet(FilterSet):
    latest_id = filters.NumberFilter(field_name='id', lookup_expr='lt')

    class Meta:
        model = models.News
        fields = ["latest_id", 'zone']


# 首页
class IndexView(DigListModelMixin, GenericViewSet):
    filter_backends = [DjangoFilterBackend]
    filterset_class = IndexFilterSet

    # 不登录也可以访问
    authentication_classes = [UserAnonTokenAuthentication]

    queryset = models.News.objects.filter(deleted=False).order_by('-id')
    serializer_class = IndexModelSerializer

